package cn.wm.server;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.wm.struct.Message;
import cn.wm.struct.MessageHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * ServerHandler
 *
 * @author wm
 * @version 1.0
 * 2021/6/25 15:43
 **/
public class ServerHandler extends SimpleChannelInboundHandler<Message> {

    private final static Log log = StaticLog.get();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("--------通道激活------------");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
        log.info("Server receive message from Client: " + message);

        Message responseMessage = new Message();
        MessageHeader header = new MessageHeader();
        header.setSessionId(2002L);
        header.setPriority((byte)2);
        header.setType((byte)1);
        responseMessage.setHeader(header);
        responseMessage.setBody("我是响应数据".getBytes());
        ctx.writeAndFlush(responseMessage);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("--------数据读取完毕------------");

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        log.error("--------服务器数据读异常------------");
        cause.printStackTrace();
        ctx.close();
    }
}
